package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.mall.enums.MallBrandStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallCategoryStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.enums.MallSupplierStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallSupplierTypeDictEnum;
import com.qqtech.qquan.mall.model.MallBrand;
import com.qqtech.qquan.mall.model.MallBrandVo;
import com.qqtech.qquan.mall.model.MallCategoryVo;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallProductQuery;
import com.qqtech.qquan.mall.model.MallProductSpecVo;
import com.qqtech.qquan.mall.model.MallProductVo;
import com.qqtech.qquan.mall.model.MallShopVo;
import com.qqtech.qquan.mall.model.MallSupplierUserQuery;
import com.qqtech.qquan.mall.model.MallSupplierUserVo;
import com.qqtech.qquan.mall.model.MallSupplierVo;
import com.qqtech.qquan.mall.service.MallBrandService;
import com.qqtech.qquan.mall.service.MallCategoryService;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.mall.service.MallSupplierUserService;
import com.qqtech.qquan.sys.controller.BaseAdminController;

@Controller
@RequestMapping(value = "/mall/product")
public class MallProductController extends BaseAdminController {
	@Resource
	private MallProductService mallProductService;

	@Resource
	private MallShopService mallShopService;

	@Resource
	private MallCategoryService mallCategoryService;

	@Resource
	private MallSupplierService mallSupplierService;

	@Resource
	private MallBrandService mallBrandService;

	@Resource
	private MallProductSpecService mallProductSpecService;

	@Resource
	private MallSupplierUserService mallSupplierUserService;

	@Override
	protected BaseService<MallProduct> getBaseService() {
		return mallProductService;
	}

	@RequestMapping(value = "/list/{shopId}", method = RequestMethod.GET)
	public String list(@PathVariable Integer shopId, Model model) {
		List<MallCategoryVo> mallCategoryVoList = mallCategoryService
				.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
		model.addAttribute("mallCategoryVoList", mallCategoryVoList);
		model.addAttribute("shopId", shopId);
		return "/mall/product-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(MallProductQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		if (query == null || query.getShopId() == null) {
			return adminPage;
		}
		String rows = (String) request.getParameter("rows"); // 每页条数
		String[] categoryIds = request.getParameterValues("categoryIds[]");
		if (categoryIds != null && categoryIds.length > 0) {
			for (int i = categoryIds.length - 1; i >= 0; i--) {
				if (StringUtil.isNotBlank(categoryIds[i])) {
					query.setCategoryId(categoryIds[i]);
					break;
				}
			}
		}
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		Page<MallProductVo> page = mallProductService.queryPageListAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 查看社区的店铺
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list4Mall", method = RequestMethod.GET)
	public String list4Mall(Model model) {
		Integer shopId = 1;
		List<MallCategoryVo> mallCategoryVoList = mallCategoryService
				.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
		model.addAttribute("mallCategoryVoList", mallCategoryVoList);
		model.addAttribute("shopId", shopId);
		return "/mall/product-list";
	}

	/**
	 * 查看社区的店铺
	 * 
	 * @param query
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list4Mall", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list4Mall(MallProductQuery query, HttpServletRequest request, HttpServletResponse response) {
		Integer shopId = 1;
		AdminPage adminPage = new AdminPage();
		if (query == null || query.getShopId() == null) {
			return adminPage;
		}
		String rows = (String) request.getParameter("rows"); // 每页条数
		String[] categoryIds = request.getParameterValues("categoryIds[]");
		if (categoryIds != null && categoryIds.length > 0) {
			for (int i = categoryIds.length - 1; i >= 0; i--) {
				if (StringUtil.isNotBlank(categoryIds[i])) {
					query.setCategoryId(categoryIds[i]);
					break;
				}
			}
		}
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		query.setShopId(shopId);
		Page<MallProductVo> page = mallProductService.queryPageListAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 查看社区的店铺
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list4Community", method = RequestMethod.GET)
	public String list4Community(Model model) {
		List<MallCategoryVo> mallCategoryVoList = mallCategoryService
				.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
		model.addAttribute("mallCategoryVoList", mallCategoryVoList);
		return "/mall/product-list4Community";
	}

	/**
	 * 查看社区的店铺
	 * 
	 * @param query
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list4Community", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list4Community(MallProductQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		String[] categoryIds = request.getParameterValues("categoryIds[]");
		if (categoryIds != null && categoryIds.length > 0) {
			for (int i = categoryIds.length - 1; i >= 0; i--) {
				if (StringUtil.isNotBlank(categoryIds[i])) {
					query.setCategoryId(categoryIds[i]);
					break;
				}
			}
		}
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		Page<MallProductVo> page = mallProductService.queryPageListAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/add/{shopId}", method = RequestMethod.GET)
	public String add(@PathVariable Integer shopId, Model model) {
		MallShopVo mallShopVo = mallShopService.getById(shopId);
		List<MallCategoryVo> firstCategoryVoList = mallCategoryService
				.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
		if (mallShopVo != null && mallShopVo.getType().intValue() == MallShopTypeDictEnum.SUPERMARKET.getCode()) {
			List<MallSupplierVo> supplierList = mallSupplierService
					.getByStatus(MallSupplierStatusDictEnum.NORMAL.getCode());
			model.addAttribute("supplierList", supplierList);
		}
		model.addAttribute("mallShopVo", mallShopVo);
		model.addAttribute("firstCategoryVoList", firstCategoryVoList);
		return "/mall/product-add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(@RequestBody MallProductVo mallProductVo, HttpServletRequest request,
			HttpServletResponse response) {
		Result ret = new Result();
		if (mallProductVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallProductVo.getName())) {
				ret.addErr("产品名称不能为空");
			} else if (mallProductVo.getName().length() > 32) {
				ret.addErr("产品名称不能超过32个字符");
			}
			if (mallProductVo.getStatus() == null) {
				ret.addErr("状态不能为空");
			}
			if (mallProductVo.getCategoryId() == null) {
				ret.addErr("分类不能为空");
			}
			if (mallProductVo.getBrandId() == null) {
				ret.addErr("品牌不能为空");
			}
			if (mallProductVo.getShopId() == null) {
				ret.addErr("店铺id不能为空");
			}
			if (StringUtils.isBlank(mallProductVo.getUnit())) {
				ret.addErr("单位不能为空");
			}

			/*
			 * if (mallProductVo.getStock() == null) { ret.addErr("库存不能为空"); }
			 * else if (mallProductVo.getStock().intValue() < 0) {
			 * ret.addErr("库存不能小于0"); } if (mallProductVo.getPrice() == null) {
			 * ret.addErr("销售价不能为空"); } else if
			 * (mallProductVo.getPrice().compareTo(BigDecimal.ZERO) < 1) {
			 * ret.addErr("销售价要大于0"); } if (mallProductVo.getMarketPrice() ==
			 * null) { ret.addErr("市场价不能为空"); } else if
			 * (mallProductVo.getMarketPrice().compareTo(BigDecimal.ZERO) < 1) {
			 * ret.addErr("市场价要大于0"); }
			 */
		}
		if (ret.checkForm()) {
			if (mallProductVo.getSupplierId() != null) {
				MallSupplierVo supplier = mallSupplierService.getById(mallProductVo.getSupplierId());
				if (supplier != null && supplier.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode()) {
					MallSupplierUserQuery msu = new MallSupplierUserQuery();
					msu.setSupplierId(mallProductVo.getSupplierId());
					List<MallSupplierUserVo> tempList = mallSupplierUserService.queryList(msu);
					if (tempList != null && tempList.size() > 1) {
						ret.addErr("本地供应商关联多个前台账户");
						return ret;
					} else if (tempList == null || tempList.size() == 0) {
						ret.addErr("本地供应商未关联前台账户");
						return ret;
					}
				}
			}
			Timestamp now = TimeUtil.now();
			MallProduct entity = new MallProduct();
			entity.setName(mallProductVo.getName().trim());
			entity.setSubtitle(mallProductVo.getSubtitle());
			entity.setStatus(mallProductVo.getStatus());
			if (mallProductVo.getBrandId().intValue() == 0) {
				entity.setBrandName(mallProductVo.getBrandName() == null ? "" : mallProductVo.getBrandName());
			} else {
				entity.setBrandId(mallProductVo.getBrandId());
				MallBrand brand = mallBrandService.getById(mallProductVo.getBrandId());
				entity.setBrandName(brand == null ? "" : brand.getName());// 冗余【品牌名称】
			}
			entity.setCategoryId(mallProductVo.getCategoryId());
			entity.setFeature("");
			entity.setIsRecommend(mallProductVo.getIsRecommend());
			entity.setMarketPrice(mallProductVo.getMarketPrice());
			entity.setPrice(mallProductVo.getPrice());
			entity.setPv(0);
			if (mallProductVo.getIsRecommend().intValue() == 2) {// 2不推荐
				entity.setRecommendOidx(0);
			} else {
				entity.setRecommendOidx(mallProductVo.getRecommendOidx());
			}
			entity.setSaleCount(0);
			entity.setFeedbackCount(0);
			entity.setShopId(mallProductVo.getShopId());
			entity.setStatusAt(now);
			entity.setStock(mallProductVo.getStock());
			if (mallProductVo.getSupplierId() == null) {
				entity.setSupplierId(0);
			} else {
				entity.setSupplierId(mallProductVo.getSupplierId());
			}
			entity.setUnit(mallProductVo.getUnit().trim());
			if (mallProductVo.getImg() == null) {
				entity.setImg("");
			} else {
				entity.setImg(mallProductVo.getImg());
			}

			entity.setNewAt(now);
			entity.setUpdAt(now);
			entity.setIsAllNew(YesNoEnum.YES.getCode());// 是全新的
			if (mallProductVo.getResume() == null) {
				entity.setResume("");
			} else {
				entity.setResume(mallProductVo.getResume());
			}
			if (mallProductVo.getResumeImg() == null) {
				entity.setResumeImg("");
			} else {
				entity.setResumeImg(mallProductVo.getResumeImg());
			}
			entity.setDiscoverRecommend(YesNoEnum.NO.getCode());
			List<MallProductSpecVo> specLst = mallProductVo.getProductSpecLst();
			if (specLst != null && specLst.size() > 0) {
				Integer totalStock = 0;
				BigDecimal minPrice = BigDecimal.ZERO;
				BigDecimal currentPrice = BigDecimal.ZERO;
				for (int i = 0; i < specLst.size(); i++) {
					MallProductSpecVo specVo = specLst.get(i);
					currentPrice = specVo.getPrice();
					if (currentPrice == null) {
						ret.addErr("商品规格价格为空");
						return ret;
					}
					if (i > 0) {
						if (minPrice.compareTo(currentPrice) == 1) {// 取最小值
							minPrice = currentPrice;
						}
					} else {
						minPrice = currentPrice;
					}
					if ("N".equals(specVo.getColor())) {
						specVo.setColor("");
					}
					if ("N".equals(specVo.getSpecName())) {
						specVo.setSpecName("");
					}
					totalStock += specVo.getStock();
				}
				entity.setPrice(minPrice);
				entity.setMarketPrice(specLst.get(0).getMarketPrice());
				entity.setStock(totalStock);
				mallProductService.handleSaveProduct(entity, specLst);
			}

		}
		return ret;
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) {
		MallProductVo mallProductVo = mallProductService.getById(id);
		if (null != mallProductVo) {
			MallShopVo mallShopVo = mallShopService.getById(mallProductVo.getShopId());
			request.setAttribute("mallShopVo", mallShopVo);
			/*
			 * List<MallCategoryVo> firstCategoryVoList = mallCategoryService
			 * .queryFirstLevelList(null);
			 */
			if (mallProductVo.getShopId().intValue() == 1) {
				List<MallSupplierVo> supplierList = mallSupplierService
						.getByStatus(MallSupplierStatusDictEnum.NORMAL.getCode());
				request.setAttribute("supplierList", supplierList);
			}
			/*
			 * if (mallProductVo.getBrandId() != null &&
			 * mallProductVo.getBrandId().intValue() != 0) { MallBrandVo
			 * mallBrandVo =
			 * mallBrandService.getById(mallProductVo.getBrandId()); if
			 * (mallBrandVo != null) {
			 * mallProductVo.setBrandName(mallBrandVo.getName()); } }
			 */
			if (StringUtil.isNotBlank(mallProductVo.getCategoryId())) {
				MallCategoryVo category = mallCategoryService.getByCategoryId(mallProductVo.getCategoryId());
				if (category != null) {
					mallProductVo.setCategoryName(category.getName());
					List<MallBrandVo> brandList = mallBrandService.findByCategoryId(mallProductVo.getCategoryId(),
							MallBrandStatusDictEnum.NORMAL.getCode());
					request.setAttribute("brandList", brandList);
					// 查询他的所有上级分类
					List<MallCategoryVo> allParentCategory = mallCategoryService
							.findAllParent(mallProductVo.getCategoryId());
					request.setAttribute("allParentCategory", allParentCategory);
				}
				List<MallCategoryVo> firstCategoryVoList = mallCategoryService
						.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
				request.setAttribute("firstCategoryVoList", firstCategoryVoList);
			}
			if (mallProductVo.getSupplierId() != null && mallProductVo.getSupplierId().intValue() != 0) {
				MallSupplierVo supplier = mallSupplierService.getById(mallProductVo.getSupplierId());
				if (supplier != null) {
					mallProductVo.setSupplierName(supplier.getName());
				}
			}
			// request.setAttribute("firstCategoryVoList", firstCategoryVoList);

			List<MallProductSpecVo> productSpecLst = mallProductSpecService.queryListByProductId(mallProductVo.getId());
			mallProductVo.setProductSpecLst(productSpecLst);

		}
		request.setAttribute("mallProductVo", mallProductVo);
		return "/mall/product-update";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(@RequestBody MallProductVo mallProductVo) {
		Result ret = new Result();
		MallProduct old = null;
		if (mallProductVo == null || mallProductVo.getId() == null) {
			ret.addErr("参数不能为空");
		} else {
			old = mallProductService.getById(mallProductVo.getId());
			if (old == null) {
				ret.addErr("不存在该产品");
			}
			if (StringUtil.isBlank(mallProductVo.getCategoryId())) {
				ret.addErr("分类不能为空");
			}
			if (StringUtil.isBlank(mallProductVo.getName())) {
				ret.addErr("请输入品牌名称");
			}
			if (mallProductVo.getStatus() == null) {
				ret.addErr("状态不能为空");
			}
			if (mallProductVo.getBrandId() == null) {
				ret.addErr("品牌不能为空");
			}
			if (StringUtils.isBlank(mallProductVo.getUnit())) {
				ret.addErr("单位不能为空");
			}
		}
		if (ret.checkForm()) {
			Timestamp now = TimeUtil.now();
			MallProduct entity = new MallProduct();
			entity.setId(mallProductVo.getId());
			entity.setName(mallProductVo.getName().trim());
			entity.setSubtitle(mallProductVo.getSubtitle());
			entity.setUpdAt(now);
			entity.setCategoryId(mallProductVo.getCategoryId());
			if (mallProductVo.getBrandId() == null) {
				entity.setBrandId(0);
			} else {
				entity.setBrandId(mallProductVo.getBrandId());
			}
			// entity.setCategoryId(mallProductVo.getCategoryId()); //分类不能修改
			// entity.setFeature("");
			entity.setIsRecommend(mallProductVo.getIsRecommend());
			// entity.setPv(0);
			if (mallProductVo.getIsRecommend().intValue() == 2) {// 2不推荐
				entity.setRecommendOidx(0);
			} else {
				entity.setRecommendOidx(mallProductVo.getRecommendOidx());
			}
			// entity.setSaleCount(0);
			entity.setShopId(mallProductVo.getShopId());
			entity.setStatus(mallProductVo.getStatus());
			if (mallProductVo.getStatus().intValue() != old.getStatus()) {
				entity.setStatusAt(now);
			}
			entity.setStock(mallProductVo.getStock());
			if (mallProductVo.getSupplierId() == null) {
				entity.setSupplierId(0);
			} else {
				entity.setSupplierId(mallProductVo.getSupplierId());
			}
			entity.setUnit(mallProductVo.getUnit().trim());
			if (mallProductVo.getImg() == null) {
				entity.setImg("");
			} else {
				entity.setImg(mallProductVo.getImg());
			}
			if (mallProductVo.getResume() == null) {
				entity.setResume("");
			} else {
				entity.setResume(mallProductVo.getResume());
			}
			if (mallProductVo.getResumeImg() == null) {
				entity.setResumeImg("");
			} else {
				entity.setResumeImg(mallProductVo.getResumeImg());
			}
			entity.setDiscoverRecommend(YesNoEnum.NO.getCode());
			List<MallProductSpecVo> specLst = mallProductVo.getProductSpecLst();
			if (specLst != null && specLst.size() > 0) {
				Integer totalStock = 0;
				BigDecimal minPrice = BigDecimal.ZERO;
				BigDecimal currentPrice = BigDecimal.ZERO;
				for (int i = 0; i < specLst.size(); i++) {
					MallProductSpecVo specVo = specLst.get(i);
					currentPrice = specVo.getPrice();
					if (currentPrice == null) {
						ret.addErr("商品规格价格为空");
						return ret;
					}
					if (i > 0) {
						if (minPrice.compareTo(currentPrice) == 1) {// 取最小值
							minPrice = currentPrice;
						}
					} else {
						minPrice = currentPrice;
					}
					if ("N".equals(specVo.getColor())) {
						specVo.setColor("");
					}
					if ("N".equals(specVo.getSpecName())) {
						specVo.setSpecName("");
					}
					totalStock += specVo.getStock();
				}
				entity.setPrice(minPrice);
				entity.setMarketPrice(specLst.get(0).getMarketPrice());
				entity.setStock(totalStock);
				mallProductService.handleUpdateProduct(entity, specLst);
			}
		}
		return ret;
	}

	@RequestMapping(value = "/imgUpload", method = RequestMethod.GET)
	public String imgUpload(Model model) {
		return "/mall/product-imgUpload";
	}

	// 设置发现首页推荐商品
	@RequestMapping(value = "/updateRecommend", method = RequestMethod.POST)
	@ResponseBody
	public Result updateRecommend(@RequestBody MallProductVo mallProductVo) {
		Result ret = new Result();
		if (mallProductVo != null) {
			if (mallProductVo.getId() == null) {
				ret.addErr("参数id不能为空");
			}
			if (mallProductVo.getDiscoverRecommend() == null) {
				ret.addErr("推荐参数不能为空");
			}
		} else {
			ret.addErr("参数不能为空");
		}
		if (ret.checkForm()) {
			MallProduct entity = new MallProduct();
			entity.setId(mallProductVo.getId());
			entity.setDiscoverRecommend(mallProductVo.getDiscoverRecommend());
			mallProductService.updateById(entity);
		}
		return ret;
	}
}
